
$SCRIPT:net = (New-Object -ComObject WScript.Network)
$SCRIPT:Shares = @()
$SCRIPT:CredList = @()

function AskQuestion ($question, $Title = "")
{
	while ($TRUE)
	{
		$answer = Read-Host "$question - [Y] or [N]: " 
		switch ($answer)
		{
			"Y" { return $TRUE}
			"" { Throw "Please enter Y or N"}
			"N" { return $FALSE }
			default { Log-Message "Unknown response '$answer'" }
		}
	}
}

function Get-ComputerFromPath([string]$path)
{
	$LOCAL:computer = $null
	if ($path -ne $null)
	{
		$LOCAL:computer = $path.split("\")[2]
	}
	if ($LOCAL:computer -ne $null)
	{
		return $LOCAL:computer
	}
	else
	{
		return ""
	}
}

function Get-NetworkShares
{
	$shareNames = @()
	$ndrives = $net.EnumNetworkDrives()
	foreach ($d in $ndrives) 
	{
		$shareNames += [string]$d
	}

	$SCRIPT:Shares = @()
	for ($i = 0;$i -lt $shareNames.Count - 1; $i = $i + 2) 
	{
		$SCRIPT:Shares += 
		@{ Drive = $shareNames[$i]
			; Path = $shareNames[$i + 1]
			; Computer = Get-ComputerFromPath($shareNames[$i + 1])
		}
	}
}

function Test-ForShare ([string]$computer)
{
	foreach ($share in $shares)
	{
		if ( $share.Computer -eq $computer )
		{
			#			Log-Message "found match $share.Path"
			return $TRUE
		}
	}
	return $FALSE
}

function Remove-Share( $share, $force = $FALSE)
{
	Log-Message "Deleting Network Share $($share.Path)" -NoNewline
	$net.RemoveNetworkDrive($share.Path, $force, $FALSE)
	Log-Message  "`t[OK]" -ForegroundColor Green
}


function Remove-Shares ($computer)
{
	foreach ($share in $shares)
	{
		if($computer -eq $share.computer)
		{
			Remove-Share $share $TRUE
		}
	}
	Get-NetworkShares
}

function Remove-NonDriveShares
{
	if ( ! ($NoPrompt))
	{
		foreach ($share in $shares) 
		{
			if ($share.Drive -eq "" )
			{
				if ( ! ($share.path -match "TSCLIENT")) #prevent removal of remote desktop shares
				{
					Log-Warning "Do you wish to remove the Mapped Drive $($share.path) ?"
					$response = ReTry "Yes or No" {AskQuestion}
					if ($response)
					{
						Remove-Share $share $TRUE
					} 
				}
			}
		}
	}
}

function findCredForUser ($username)
{
	foreach ($cred in $SCRIPT:CredList)
	{
		if ($cred.UserName -eq $username)
		{
			return $cred
		}
	}
}

function GetCredForComputer ($computer, $domain)
{
	$defaultDomain = $domain
	if ([system.string]::IsNullOrEmpty($defaultDomain))
	{
		$defaultUser = "$($net.UserName)"
	}
	else
	{
	$defaultUser = "$defaultDomain\$($net.UserName)"
	}
	$cred = findCredForUser $defaultUser

	if ($cred -eq $null)
	{
		if (-not $NoPrompt)
		{
		Log-Warning "Enter Credentials for $computer"
		$cred = Get-Credential $defaultUser
		}
		else
		{
			$usernamePath = [system.io.path]::combine("\\hdc.net\thematrix\Deployment Packages\DeploymentManagement\$($ProductName)", "$($TargetEnv).username.txt")
			if (Test-Path $usernamePath)
			{
				log-message "Username file $($usernamePath) found and used."
				$defaultUser = Get-Content $usernamePath
				log-message "$($defaultUser) will be used."
			}
			$ProductName = $Deploymentinfo.variables.ProjectDashboardProductName
			$passwordPath = [system.io.path]::combine("\\hdc.net\thematrix\Deployment Packages\DeploymentManagement\$($ProductName)", "$($TargetEnv).password.txt")
			if (Test-Path $passwordPath)
			{
				$password = Get-Content $passwordPath | ConvertTo-SecureString
				$cred = New-Object system.Management.Automation.PSCredential $defaultUser,$password
			}
			else
			{
				Throw "Password file $($TargetEnv).password.txt was not found. Create secure password file or verify matrix access."
			}
		}
	}
	if ($cred.GetNetworkCredential().Password -eq "" -or $cred.GetNetworkCredential().Password -eq $null)
	{
		Throw "Password cannot be blank" 
	}
	return $cred
}

function Add-Cred ($newCred)
{
	if( ( findCredForUser $newCred.UserName ) -eq $null)
	{
		$SCRIPT:CredList += $newCred
	}
}

function Create-NetworkShare ([string]$path, $domain, $force = $FALSE)
{
	$computer = Get-ComputerFromPath $path
	if ( Test-ForShare $computer )
	{
		if ( ! (Test-Path $path))
		{
			$LOCAL:msg = "Share already exists for computer $computer but does not allow access to $path"
			if( $force )
			{
				log-Warning $msg
				log-Warning "Deleting Shares to $computer"
				Remove-Shares $computer
			}
			else
			{
				log-Error $msg
				exit
			}
		}
	}

	$cred = $SCRIPT:CredList[0]
	if ($cred -eq $null)
	{
		$cred = GetCredForComputer $computer $domain
	}

	Log-Message "Creating network share for '$path': " -NoNewline
	$net.MapNetworkDrive("", $path, $FALSE, $cred.UserName, $cred.GetNetworkCredential().Password)
	if ( Test-Path $path)
	{
		Log-Message "[OK]" -ForegroundColor Green
	}
	else 
	{
		Remove-Shares $computer
		$cred = $null
		Throw "Mapped drive completed but does not allow access to $path. "
	}
	Add-Cred $cred

	Get-NetworkShares
}

function Assure-PathAccess ($path, $domain) 
{
	if (-not($NoPrompt) -and -not(Test-Path $path) )
	{
		$rootpath = ($path.root).fullname
		if ( -not (Test-Path $rootpath))
		{
			Create-NetworkShare $path $domain -force $TRUE
		}
		elseif (Test-Path $rootpath)
		{
			Log-Message "Access to $rootpath successful"
		}

	}
	elseif ( ($NoPrompt) -and -not(Test-Path $path))
	{
		Create-NetworkShare $path $domain -force $TRUE 
	}
	elseif (Test-Path $path)
	{
		Log-Message "Access to $path successful"
	}
}

Get-NetworkShares
